package flc.ast.fragment.edit;

import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.imgedit.ImgEditActivity;
import com.stark.imgedit.ModuleConfig;
import com.stark.imgedit.utils.Matrix3;
import com.stark.imgedit.view.CropImageView;
import com.stark.imgedit.view.imagezoom.ImageViewTouchBase;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseEditFragment;
import flc.ast.R;
import flc.ast.adapter.CropAdapter;
import flc.ast.bean.MyCutBean;
import flc.ast.databinding.FragmentCropBinding;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.RxUtil;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link CropFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class CropFragment extends BaseEditFragment<FragmentCropBinding> {

    public static final int INDEX = ModuleConfig.INDEX_CROP;
    public CropImageView mCropView;
    private CropAdapter cropAdapter;
    private int oldPosition;

    public static CropFragment newInstance() {
        CropFragment fragment = new CropFragment();
        return fragment;
    }

    @Override
    public void onShow() {
        mImgEditActivity.mode = ImgEditActivity.MODE_CROP;
        if (cropAdapter != null) {
            cropAdapter.getItem(oldPosition).setSelect(false);
            cropAdapter.getItem(0).setSelect(true);
            oldPosition = 0;
            cropAdapter.notifyDataSetChanged();
        }
        mImgEditActivity.mCropView.setVisibility(View.VISIBLE);
        mImgEditActivity.mImgView.setImageBitmap(mImgEditActivity.getMainBit());
        mImgEditActivity.mImgView.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);
        mImgEditActivity.mImgView.setScaleEnabled(false);// 禁用缩放

        //  bug  fixed  https://github.com/siwangqishiq/ImageEditor-Android/issues/59
        // 设置完与屏幕匹配的尺寸  确保变换矩阵设置生效后才设置裁剪区域
        mImgEditActivity.mImgView.post(new Runnable() {
            @Override
            public void run() {
                final RectF r = mImgEditActivity.mImgView.getBitmapRect();
                mImgEditActivity.mCropView.setCropRect(r);
            }
        });
    }

    @Override
    public void backToMain() {
        mImgEditActivity.mode = ImgEditActivity.MODE_NONE;
        mCropView.setVisibility(View.GONE);
        mImgEditActivity.mImgView.setScaleEnabled(true);// 恢复缩放功能
        mCropView.setRatioCropRect(mImgEditActivity.mImgView.getBitmapRect(), 1);
        mImgEditActivity.showFunc();
    }

    @Override
    protected int onCreate() {
        return R.layout.fragment_crop;
    }

    @Override
    protected void initView() {
        mDataBinding.ivCancel.setOnClickListener(this);
        mDataBinding.ivApply.setOnClickListener(this);

        mCropView = mImgEditActivity.mCropView;
        mDataBinding.rvRatio.setLayoutManager(new LinearLayoutManager(mImgEditActivity, LinearLayoutManager.HORIZONTAL, false));
//        mDataBinding.rvRatio.addItemDecoration(new RecycleViewDivider(mImgEditActivity, LinearLayoutManager.HORIZONTAL,
//                DensityUtil.dip2px(mImgEditActivity, 16), Color.parseColor("#00000000")));
        cropAdapter = new CropAdapter();
        cropAdapter.setOnItemClickListener(this);
        mDataBinding.rvRatio.setAdapter(cropAdapter);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivCancel://取消
                backToMain();
                break;
            case R.id.ivApply://确定
                applyCropImage();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        cropAdapter.getItem(oldPosition).setSelect(false);
        cropAdapter.getItem(position).setSelect(true);
        oldPosition = position;
        cropAdapter.notifyDataSetChanged();
        mCropView.setRatioCropRect(mImgEditActivity.mImgView.getBitmapRect(), cropAdapter.getItem(position).getRatio());
    }

    @Override
    protected void initData() {
        //裁剪数据
        List<MyCutBean> listCut = new ArrayList<>();
        listCut.add(new MyCutBean("1:1", R.drawable.a1_1, 1f, true));
        listCut.add(new MyCutBean("2:3", R.drawable.a2_3, 2f / 3f, false));
        listCut.add(new MyCutBean("3:2", R.drawable.a3_2, 3f / 2f, false));
        listCut.add(new MyCutBean("3:4", R.drawable.a3_4, 3f / 4f, false));
        listCut.add(new MyCutBean("4:3", R.drawable.a4_3, 4f / 3f, false));
        listCut.add(new MyCutBean("9:16", R.drawable.a9_16, 9f / 16f, false));
        cropAdapter.setList(listCut);
        onShow();
    }

    /**
     * 保存剪切图片
     */
    private void applyCropImage() {
        showDialog(getString(com.stark.common.res.R.string.handling));
        RxUtil.create(new RxUtil.Callback<Bitmap>() {
            @Override
            public void doBackground(ObservableEmitter<Bitmap> emitter) {
                RectF cropRect = mCropView.getCropRect();// 剪切区域矩形
                Matrix touchMatrix = mImgEditActivity.mImgView.getImageViewMatrix();
                float[] data = new float[9];
                touchMatrix.getValues(data);// 底部图片变化记录矩阵原始数据
                Matrix3 cal = new Matrix3(data);// 辅助矩阵计算类
                Matrix3 inverseMatrix = cal.inverseMatrix();// 计算逆矩阵
                Matrix m = new Matrix();
                m.setValues(inverseMatrix.getValues());
                m.mapRect(cropRect);// 变化剪切矩形

                Bitmap resultBit = Bitmap.createBitmap(mImgEditActivity.getMainBit(),
                        (int) cropRect.left, (int) cropRect.top,
                        (int) cropRect.width(), (int) cropRect.height());
                emitter.onNext(resultBit);
            }

            @Override
            public void accept(Bitmap bitmap) {
                dismissDialog();
                if (bitmap == null) return;
                mImgEditActivity.changeMainBitmap(bitmap, true);
                mImgEditActivity.mCropView.setCropRect(mImgEditActivity.mImgView.getBitmapRect());
                backToMain();
            }
        });
    }

}